import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Space, Button, Tabs, Modal, message, Typography } from 'antd';
import { connect, useIntl } from 'umi';
import Invoice from './Invoice';
import QuickMenu from '@/components/QuickMenu';
import OperpQuery from '@/components/OperpQuery';
import { convertCurrency } from '@/utils/utils';

const { TabPane } = Tabs;
const { Text } = Typography;

const ViewPage: React.FC<any> = (props) => {
  const [selectedRows, setSelectedRows] = useState([]);
  const [freshNum, setFreshNum] = useState(1);
  const [totalAmt, setTotalAmt] = useState<any>(0);
  const [totalAmt2, setTotalAmt2] = useState<any>(0);
  const [totalAmt3, setTotalAmt3] = useState<any>(0);
  const [totalProfit, setTotalProfit] = useState<any>(0);
  const [visible2, setVisible2] = useState(false);
  const [invoiceType, setInvoiceType] = useState('');
  const intl = useIntl();

  useEffect(() => {
    // componentDidMount
  }, []);

  const swithModel = (visible2: boolean) => {
    if (selectedRows.length <= 0) {
      message.warning(intl.formatMessage({ id: 'pages.selectAtLeastOneRecord' }));
      return;
    }
    setVisible2(visible2);
  };

  const onSelectChange = (selectedRowKeys: any, selectedRows: any) => {
    setSelectedRows(selectedRows);
  };

  const tabChange = (key: any) => {
    setInvoiceType(key);
  };

  const onInvLoad = (data: any) => {
    let totalAmt: number = 0;
    data.forEach((element: any) => {
      totalAmt += Math.abs(element.ExtCost);
    });
    const result = Math.abs(totalAmt).toFixed(2);
    setTotalAmt(result);
  };

  const onInvLoad2 = (data: any) => {
    let totalAmt: number = 0;
    data.forEach((element: any) => {
      totalAmt += Math.abs(element.ExtCost);
    });
    const result = Math.abs(totalAmt).toFixed(2);
    setTotalAmt2(result);
  };

  const onInvLoad3 = (data: any) => {
    let totalAmt: number = 0;
    let totalSale: number = 0;
    let totalPO: number = 0;
    data.forEach((element: any) => {
      totalAmt += Math.abs(element.ExtCost);
      if (element.TranQty < 0) {
        totalSale += Math.abs(element.ExtCost);
      } else {
        totalPO += element.ExtCost;
      }
    });
    const result = Math.abs(totalAmt).toFixed(2);
    setTotalAmt3(result);
    setTotalProfit((totalSale - totalPO).toFixed(2));
  };

  const rowSelection = {
    onChange: onSelectChange,
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Tabs
          tabBarExtraContent={
            <Space>
              <QuickMenu
                path="/Finance/FinRcvPay"
                icon="icon-money_transfer"
                title="pages.FinRcvPay"
              />
              <Button type="primary" onClick={() => swithModel(true)}>
                {intl.formatMessage({ id: 'pages.invoice.entry' })}
              </Button>
              <Button type="primary" danger onClick={() => swithModel(true)}>
                {intl.formatMessage({ id: 'pages.invoice.revoke' })}
              </Button>
            </Space>
          }
          defaultActiveKey="INV"
          onChange={tabChange}
        >
          <TabPane tab={intl.formatMessage({ id: 'pages.accountsReceivable' })} key="INV">
            <OperpQuery
              rowSelection={rowSelection}
              sysReportName="ReportFinIn"
              scroll={{ x: 'max-content', y: '600px' }}
              freshNum={freshNum}
              bordered
              onload={(d) => onInvLoad(d)}
              footer={() => (
                <Space>
                  <span>
                    {intl.formatMessage({ id: 'pages.totalReceivables' })}
                    <Text type="danger" strong>
                      {totalAmt}
                    </Text>{' '}
                    {intl.formatMessage({ id: 'pages.currencyUnit' })}
                  </span>
                  <span>
                    <Text type="success" strong>
                      ({convertCurrency(totalAmt)})
                    </Text>
                  </span>
                </Space>
              )}
            />
          </TabPane>
          <TabPane tab={intl.formatMessage({ id: 'pages.accountsPayable' })} key="ONV">
            <OperpQuery
              rowSelection={rowSelection}
              sysReportName="ReportFinOut"
              scroll={{ x: 'max-content', y: '600px' }}
              freshNum={freshNum}
              bordered
              onload={(d) => onInvLoad2(d)}
              footer={() => (
                <Space>
                  <span>
                    {intl.formatMessage({ id: 'pages.totalReceivables' })}
                    <Text type="danger" strong>
                      {totalAmt2}
                    </Text>{' '}
                    {intl.formatMessage({ id: 'pages.currencyUnit' })}
                  </span>
                  <span>
                    <Text type="success" strong>
                      ({convertCurrency(totalAmt2)})
                    </Text>
                  </span>
                </Space>
              )}
            />
          </TabPane>
          <TabPane tab={intl.formatMessage({ id: 'pages.issuedInvoice' })} key="Invced">
            <OperpQuery
              rowSelection={rowSelection}
              sysReportName="ReportInvoiced"
              scroll={{ x: 'max-content', y: '600px' }}
              freshNum={freshNum}
              bordered
              onload={(d) => onInvLoad3(d)}
              footer={() => (
                <Space>
                  <span>
                    {intl.formatMessage({ id: 'pages.totalInvoice' })}
                    <b>{totalAmt3}</b>
                    {intl.formatMessage({ id: 'pages.currencyUnit' })}
                  </span>
                  <span>
                    {intl.formatMessage({ id: 'pages.grossProfit' })}
                    <Text type="danger" strong>
                      {totalProfit}
                    </Text>
                    {intl.formatMessage({ id: 'pages.currencyUnit' })}
                  </span>
                  <span>
                    <Text type="success" strong>
                      ({convertCurrency(totalProfit)})
                    </Text>
                  </span>
                </Space>
              )}
            />
          </TabPane>
        </Tabs>
      </Card>
      <Modal
        width={900}
        title={intl.formatMessage({ id: 'pages.invoice.entry' })}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => swithModel(false)}
        footer={false}
      >
        <Invoice data={selectedRows} invoiceType={invoiceType} />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
